//
//  StatusListViewModel.m
//  weibo110
//
//  Created by 臧松 on 15/12/30.
//  Copyright © 2015年 臧松. All rights reserved.
//

#import "StatusListViewModel.h"
#import "NetworkTools.h"
#import "StatusViewModel.h"
#import "SDWebImageManager.h"
#import "SDWebImageDownloader.h"
@implementation StatusListViewModel


-(void)loadStatusDatafinished:(void (^)(BOOL isSuccessed))finished{
    
    [[NetworkTools sharedTools] loadStatusfinished:^(id result, NSError *error) {
        if (error != nil) {
            NSLog(@"出错了");
            finished(NO);
            return ;
        }
        
        NSArray * array = result[@"statuses"];
        
        if (array != nil) {
            
            NSMutableArray * arrayM = [NSMutableArray array];
            for (NSDictionary * dict in array) {
                Status * status = [Status statusWithDict:dict];
                 StatusViewModel * viewModel = [[StatusViewModel alloc]initWithStatus:status];
                
                [arrayM addObject:viewModel];
                
                }
            self.statusList = arrayM;
            
            
            [self cacheSingleImage:arrayM finished:finished];
            
                       
        }else{
            
            NSLog(@"数据格式错误");
            finished(NO);
            return;
        }
    }];

}
-(void)cacheSingleImage:(NSArray*)viewModel finished:(void (^)(BOOL isSuccessed))finished{
    // 创建调度组
    dispatch_group_t group = dispatch_group_create();
    // 缓存数据长度
    __block float dataLength = 0;
    
    for (StatusViewModel * vm in viewModel) {
        if (vm.thumbnailUrls.count != 1) {
            continue;
        }
        NSLog(@"%@",vm.thumbnailUrls.firstObject);

       
        // 入组
        dispatch_group_enter(group);
        [[SDWebImageManager sharedManager]downloadImageWithURL:vm.thumbnailUrls.firstObject options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (image != nil) {
                NSData * data = UIImagePNGRepresentation(image);
               
                dataLength += data.length;
            }
            // 出租
            dispatch_group_leave(group);
        }];
}
    // 监听调度组完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
        NSLog(@"缓存完成%lf K",dataLength/1024);
         // 完成回调
        finished(YES);
    });
}
@end

